package day6;

import org.junit.Test;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;

public class CardDealTest {

    @Test
    public void testDealCards() {
        // 1. 创建一副新牌
        NewCard deck = new NewCard();

        // 2. 创建三个玩家
        Player[] players = new Player[3];
        players[0] = new Player("玩家A");
        players[1] = new Player("玩家B");
        players[2] = new Player("玩家C");

        // 3. 洗牌并发牌
        CardDealer.dealCards(deck, players);

        // 4. 显示每个玩家的手牌
        for (Player player : players) {
            player.displayCards();
        }
    }

    // 添加CardDealer类
    private static class CardDealer {
        /**
         * 洗牌并发牌给玩家
         * @param deck 扑克牌
         * @param players 玩家数组
         */
        public static void dealCards(NewCard deck, Player[] players) {
            // 1. 洗牌
            shuffleCards(deck.cards);

            // 2. 发牌 - 前51张牌平均分给三个玩家，每人17张
            int playerIndex = 0;
            for (int i = 0; i < 51; i++) {
                players[playerIndex].addCard(deck.cards[i]);
                playerIndex = (playerIndex + 1) % 3; // 轮流发给三个玩家
            }

            // 3. 剩余3张作为底牌
            System.out.println("底牌:");
            for (int i = 51; i < 54; i++) {
                System.out.print(deck.cards[i] + " ");
            }
            System.out.println("\n");
        }

        /**
         * 洗牌算法 - Fisher-Yates洗牌算法
         * @param cards 扑克牌数组
         */
        private static void shuffleCards(Card[] cards) {
            Random random = new Random();
            for (int i = cards.length - 1; i > 0; i--) {
                int j = random.nextInt(i + 1);
                // 交换cards[i]和cards[j]
                Card temp = cards[i];
                cards[i] = cards[j];
                cards[j] = temp;
            }
        }
    }

    private class Player {
        private String name;
        private List<Card> cards;

        public Player(String name) {
            this.name = name;
            this.cards = new ArrayList<>();
        }

        public void addCard(Card card) {
            if (card != null) {
                cards.add(card);
            }
        }

        public void displayCards() {
            System.out.println(name + "的手牌:");
            for (int i = 0; i < cards.size(); i++) {
                System.out.print(cards.get(i) + " ");
                // 每13张牌换一行，便于阅读
                if ((i + 1) % 13 == 0) {
                    System.out.println();
                }
            }
            System.out.println("\n总共: " + cards.size() + " 张牌\n");
        }
    }
}
